<?php

class CUCS2String extends CString {
	var $Buffer;
	
	function Init($buf) {
		$this->Buffer = $buf;
	}
	
	function Length() {
		return strlen($this->Buffer) / 2;
	}
	
	function &Characters($from, $len) {
		$x = &new CUCS2Iterator($this, $from, $len);
		return $x;
	}
	
	function MakeNewFromBuffer($buf) {
		if ((strlen($buf) % 2) == 1)
			return null;
		
		return new CUCS2String($buf);
	}
	
	function FastBufferOfEncoding($enc) {
		if ($enc == kUCS2LE)
			return $this->Buffer;
		else
			return null;
	}
}

class CUCS2Iterator extends CCharIterator {
	var $Str;
	var $From;
	var $Len;
	var $I = 0;
	
	function Init($str, $from, $len) {
		$this->Str = $str;
		$this->From = $from * 2;
		$this->Len = min($len * 2, strlen($str->Buffer));
	}
	
	function NextChar() {
		if ($this->I >= $this->Len)
			return null;
		
		$bytea = ord($this->Str->Buffer{$this->From + $this->I});
		$byteb = ord($this->Str->Buffer{$this->From + $this->I + 1});
		$c = $bytea | ($byteb << 8);
		$this->I += 2;
		
		return $c;
	}
}

class CUCS2Encoder extends CBufferEncoder {	
	function AppendString($x) {
		$this->FastAppendIfEncoding($x, kUCS2LE)
			or parent::AppendString($x);
	}
	
	function BytesForChar($c) {
		if ($c > 0xFFFF) return null;
		
		$bytea = $c & 0xFF;
		$byteb = ($c & 0xFF00) >> 8;
		return chr($bytea) . chr($byteb);
	}
	
	function ReplacementBytes() {
		return chr(0xFD) . chr(0xFF); // U+FFFD REPLACEMENT CHARACTER
	}
	
	function AsString() {
		return CUCS2String::MakeNewFromBuffer($this->Buffer);
	}
}

?>